package com.trsj.lnsj.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.entity.ActivityDTO;
import com.trsj.lnsj.entity.CommentDTO;
import com.trsj.lnsj.service.imp.ActivityService;
import com.trsj.lnsj.service.imp.CommentService;
import com.trsj.lnsj.util.QiNiu;
import com.trsj.lnsj.util.ResponseHelper;
import com.trsj.lnsj.util.UploadHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 活动管理
 * @author winte
 *
 */
@RestController
@Api("活动相关相关的api")
@RequestMapping(value = "/api/activity/*")
@CrossOrigin
public class ActivityController {

    private Logger logger = LoggerFactory.getLogger(ActivityController.class);
    @Autowired
    private ActivityService actService;
    @Autowired
    private Environment env;
    @Autowired
    private CommentService commentService;

    @RequestMapping(value = "/addcommont", method = RequestMethod.POST)
    public DataResponse addCommnet(@RequestBody  CommentDTO comment) {
        DataResponse resp = null;
        try {
            comment.setCreateTime(new Date());
            commentService.add(comment);
            resp=ResponseHelper.getSuccessResponse(comment);
        }catch(Exception e ){
            e.printStackTrace();
            resp=ResponseHelper.getResponse(MsgStatus.SYS_ERROR, "查询活动失败");
            logger.error("增加评论失败",e);
        }

        return resp;
    }

    @RequestMapping(value = "/commont", method = RequestMethod.GET)
    public DataResponse addCommnet(Long activityId,@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="5")int pageSize) {
        DataResponse resp = null;
        pageNum=pageNum-1;
        PageRequest pageRequest=new PageRequest(pageNum, pageSize);
        try {

            resp=ResponseHelper.getSuccessResponse(commentService.findByActivityId(activityId,pageRequest));
        }catch(Exception e ){
            e.printStackTrace();
            resp=ResponseHelper.getResponse(MsgStatus.SYS_ERROR, "查询活动失败");
            logger.error("增加评论失败",e);
        }

        return resp;
    }


    @RequestMapping(value = "/moreactivity", method = RequestMethod.GET)
    public DataResponse getMoreActivity(Long activityId,String happyNo,@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="5")int pageSize) {
    	 DataResponse resp = null;
    	  pageNum=pageNum-1;
          PageRequest pageRequest=new PageRequest(pageNum, pageSize);
          List<ActivityDTO> resList=null;
          Page<ActivityDTO> page = null;
        		  try {
        			  resList =actService.moreActivity(activityId,happyNo, pageRequest.getOffset(), pageRequest.getPageSize());
        			  int total = 0;
        	            page = new PageImpl<ActivityDTO>(resList, pageRequest, total);
        	            resp = ResponseHelper.getSuccessResponse(page);
        		  }catch(Exception e ){
    		  e.printStackTrace();
	    	   resp=ResponseHelper.getResponse(MsgStatus.SYS_ERROR, "查询活动失败");
	    	  logger.error("查询我收藏活动失败",e);
    	}
          
    	return resp;
    }
    
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public DataResponse findById(Long id) {
    	
    	 DataResponse resp = null;
    	 try {
    		 resp=actService.findById(id);
    	    }catch(Exception e) {
    	    	   e.printStackTrace();
    	    	   resp=ResponseHelper.getResponse(MsgStatus.SYS_ERROR, "查询活动失败");
    	    	  logger.error("查询我收藏活动失败",e);
    	       }
    	return resp;
    }
    
    
    @RequestMapping(value = "/list_by_user_created", method = RequestMethod.GET)
    public DataResponse listMyCreatedActivity(@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="10") int pageSize,String actOrganiser) {
        DataResponse resp = null;
        pageNum=pageNum-1;
        PageRequest pageRequest=new PageRequest(pageNum, pageSize);
       try {
    	   resp=actService.listMyCreatedActivity(actOrganiser,pageRequest);
       }catch(Exception e) {
    	   e.printStackTrace();
    	   resp=ResponseHelper.getResponse(MsgStatus.SYS_ERROR, "查询我收藏活动失败");
    	  logger.error("查询我收藏活动失败",e);
       }
        return resp;
    }
    
    
    @RequestMapping(value = "/list_by_name", method = RequestMethod.GET)
    public DataResponse listByName(String name) {
        DataResponse resp = null;
       
        
        return new DataResponse(MsgStatus.STATUS_OK, actService.findByNameLike(name));
    }
    
    /**
     * 获取活动列表
     * @param actDto
     * @param session
     * @return
     */
//    @ApiOperation(value = "获取活动列表", notes = "获取活动列表")
//    @RequestMapping(value = "/list", method = RequestMethod.GET)
//    public DataResponse list(@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="10") int pageSize, String type,String q, HttpServletRequest request, HttpSession session) {
//        DataResponse resp = null;
//        pageNum=pageNum-1;
//        PageRequest pageRequest =new PageRequest(pageNum, pageSize);
//        Page<ActivityDTO> resList = null;
//        try {
//            resList = actService.selectActivity(pageRequest,type,q);
//        } catch (Exception e) {
//            e.printStackTrace();
//            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
//        }
//        return ResponseHelper.getSuccessResponse(resList);
//    }
    @ApiOperation(value = "获取活动列表", notes = "获取活动列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public DataResponse list(@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="10") int pageSize, @RequestParam(defaultValue="") String type, @RequestParam(defaultValue="") String city,@RequestParam(defaultValue="")  String q,@RequestParam(defaultValue="0") Float lowprice,@RequestParam(defaultValue="0") Float highprice, HttpServletRequest request, HttpSession session) {
        DataResponse resp = null;
        pageNum = pageNum - 1;
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);
        Page<ActivityDTO> page = null;
        List<ActivityDTO> resList = null;
        try {
            resList = actService.selectActivity(pageRequest.getOffset(), pageRequest.getPageSize(), type, city, q,lowprice,highprice);
            int total = 0;
            page = new PageImpl<ActivityDTO>(resList, pageRequest, total);
            resp = ResponseHelper.getSuccessResponse(page);

        } catch (Exception e) {
            e.printStackTrace();
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }
    /**
     * 上传文件
     * @param actDto
     * @param session
     * @return
     * add by longky @20180828
     */
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public DataResponse upload(HttpServletRequest request) {
         List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("file");
         String Url= setSingleImage(file);
         if(StringUtils.isEmpty(Url)) {
            
        return new DataResponse(MsgStatus.STATUS_FAILED);
                 }
        return new DataResponse(MsgStatus.STATUS_OK, Url);
    }

    /**
     * 创建活动
     * @param actDto
     * @param session
     * @return
     * edit by longky @20180827
     */
    @ApiOperation(value = "增加活动", notes = "增加活动")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public DataResponse add(@Validated ActivityDTO actDto) {
    	 DataResponse res =null;
    	try {
        res = actService.addActivity(actDto);}
    	catch(Exception e) {
    		e.printStackTrace();
    		logger.error("添加活动失败",e);
    		
    	}
       return res;
   }
    
    /**
     * 修改活动
     * @param actDto
     * @param session
     * @return
     * edit by longky @20180827
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public DataResponse update(ActivityDTO actDto) {
    	DataResponse res=null;
       try { 
    	   res = actService.updateActivity(actDto);
       }catch (Exception e) {
    	   logger.error("修改活动失败",e);
    	   e.printStackTrace();
	}
       
       return res;
   }
    
    /**
     * 活动报名
     * @param actDto
     * @param session
     * @return
     * edit by longky @20180827
     */
    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public DataResponse signUp(@RequestParam(name="activityId" ,required=true)Long activityId,@RequestParam(name="userId" ,required=true)Long userId,String Participants) {
       String res = actService.signUp(activityId, userId,Participants);
       if(res.equals("-2")) {
    	   return new DataResponse(MsgStatus.PARAMS_INVALID,"不能重复报名"); 
       }
       if(res.equals("-3")) {
    	   return new DataResponse(MsgStatus.PARAMS_INVALID,"活动不存在"); 
       }
       return new DataResponse(MsgStatus.STATUS_OK,res);
   }
    
    
    

    public int setImage(ActivityDTO actDto, List<MultipartFile> imgFiles) {
        //imgFile.getInputStream();
        StringBuilder imgSb = new StringBuilder();
        if (imgFiles!=null) {
            for (MultipartFile imgFile:imgFiles) {
                if (imgFile != null && StringUtils.isNotBlank(imgFile.getName())) {
                    String fileName = String.valueOf(System.currentTimeMillis()) + imgFile.getOriginalFilename().replaceAll(";", "f");
                    String tmpPath = env.getProperty("zlnsj.temp.file.path");
                    String path = tmpPath + actDto.getHappyNo();
                    File fileDir = new File(path);
                    if (!fileDir.exists()) {
                        fileDir.mkdir();
                    } else if (fileDir.isDirectory()) {
                        File imgFileTemp = new File(path + File.separator + fileName);
                        if (!imgFileTemp.exists()) {
                            try {
                                imgFileTemp.createNewFile();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                logger.error("上传 imgFileTemp 错误 ",e);
                                return  -1;
                            }
                        }
                        InputStream in = null;
                        try {
                            in = imgFile.getInputStream();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            logger.error("imgFile.getInputStream() error ",e);
                            try {
                                in.close();
                            } catch (IOException e2) {
                                // TODO Auto-generated catch block
                                e2.printStackTrace();
                            }
                            return  -1;
                        }
                        UploadHelper.writeToNewFile(in, imgFileTemp.getAbsolutePath());
                        try {
                            in.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return -1;
                        }
                        QiNiu.uploadFile(imgFileTemp, imgFileTemp.getName(), QiNiu.bucket, 2);
                        if (StringUtils.isEmpty(imgSb.toString())) {
                            imgSb.append(env.getProperty("zlnsj.activity.image.path") + "/" + imgFileTemp.getName());
                        } else {
                            imgSb.append(";" + env.getProperty("zlnsj.activity.image.path") + "/" + imgFileTemp.getName());
                        }
                    }
                    fileDir.delete();
                    actDto.setImageAddr(imgSb.toString());
                }
            }
        }
        return 1;
    }

    public String setSingleImage( List<MultipartFile> imgFiles) {
        //imgFile.getInputStream();
        StringBuilder imgSb = new StringBuilder();
        if (imgFiles!=null) {
            for (MultipartFile imgFile:imgFiles) {
                if (imgFile != null && StringUtils.isNotBlank(imgFile.getName())) {
                    String fileName = String.valueOf(System.currentTimeMillis()) + imgFile.getOriginalFilename();
                    String tmpPath = env.getProperty("zlnsj.temp.file.path");
                    String path = tmpPath;
                    File fileDir = new File(path);
                    if (!fileDir.exists()) {
                        fileDir.mkdir();
                    } else if (fileDir.isDirectory()) {
                        File imgFileTemp = new File(path + File.separator + fileName);
                        if (!imgFileTemp.exists()) {
                            try {
                                imgFileTemp.createNewFile();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                   logger.error("上传 imgFileTemp 错误 ",e);
                                e.printStackTrace();
                            return "";
                            }
                        }
                        InputStream in = null;
                        try {
                            in = imgFile.getInputStream();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            try {
                                in.close();
                            } catch (IOException e2) {
                                // TODO Auto-generated catch block
                                e2.printStackTrace();
                                logger.error("imgFile.getInputStream() error ",e);
                                
                            }
                            return "";
                        }
                        UploadHelper.writeToNewFile(in, imgFileTemp.getAbsolutePath());
                        try {
                            in.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        QiNiu.uploadFile(imgFileTemp, imgFileTemp.getName(), QiNiu.bucket, 2);
                        if (StringUtils.isEmpty(imgSb.toString())) {
                            imgSb.append(env.getProperty("zlnsj.activity.image.path") + "/" + imgFileTemp.getName());
                        } else {
                            imgSb.append(";" + env.getProperty("zlnsj.activity.image.path") + "/" + imgFileTemp.getName());
                        }
                    }
                    fileDir.delete();
                }
            }
        }
        return imgSb.toString();
    }

    /**
     * 获取用户参与活动信息
     * @param happyNo
     * @param joinType
     * @return
     */
    @RequestMapping(value = "/getUserJoinActivityInfo", method = RequestMethod.POST)
    public DataResponse getUserJoinActivityInfo(@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="10") int pageSize, @RequestParam(required=true) String happyNo, @RequestParam(required=true) short joinType) {
        DataResponse resp = actService.getUserJoinActivityInfo(pageNum, pageSize, happyNo, joinType);
        return resp;
    }

    /**
     * 获取好友活动列表
     * @param happyNo
     * @param actid
     * @return
     */
    @RequestMapping(value = "/getFriendActivity", method = RequestMethod.POST)
    public DataResponse getFriendActivity(@RequestParam(defaultValue="1") int pageNum, @RequestParam(defaultValue="10") int pageSize, String happyNo) {
        DataResponse resp = actService.getFriendActivity(pageNum, pageSize, happyNo);
        return resp;
    }

}
